package com.hcq.service;


import com.alibaba.fastjson.JSON;
import com.common.base.BaseService;
import com.common.entity.PageParam;
import com.common.entity.Role;
import com.common.entity.Rsp;
import com.common.entity.User;
import com.common.util.JWTUtil;
import com.common.util.Secret;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hcq.mapper.AreaMapper;
import com.hcq.mapper.UserMapper;
import com.common.entity.Area;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Transactional(rollbackFor = Exception.class)
@Service
public class UserServiceImpl implements BaseService<User> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private AliMsgServiceImpl aliMsgService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public PageInfo<User> searchSomeByPage(PageParam<User> pageParam) {
        if(!StringUtils.isEmpty(pageParam.getSuperSearchKeyWord())){
            //执行高级检索
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }


            List<User> userList=userMapper.superSearch(pageParam.getSuperSearchKeyWord());
            PageInfo<User> userPageInfo = new PageInfo<>(userList);

            return userPageInfo;

        }else{
            //分页
            PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
            //排序
            for(int i=0;i<pageParam.getOrderParams().length;i++){
                PageHelper.orderBy(pageParam.getOrderParams()[i]);
            }

            pageParam.getModel().setDeleted(User.NO_DELETED);
            List<User> userList=userMapper.searchSomeByPage(pageParam.getModel());
            PageInfo<User> userPageInfo = new PageInfo<>(userList);

            return userPageInfo;
        }
    }

    @Override
    public User getOneById(String id) {
        return userMapper.getOneById(id);
    }

    @Override
    public Rsp addOne(User user) {
        //初始化用户参数
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        user.setId(id);
        user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        user.setPoints(0);
        user.setStatus(User.UN_LOG_ON);
        user.setDeleted(User.NO_DELETED);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        int result = userMapper.addOne(user);
        return result == 1?Rsp.success("添加成功"):Rsp.fail().msg("添加失败");
    }

    @Override
    public Rsp update(User user) {
        int result = userMapper.update(user);
        return result == 1?Rsp.success("修改成功"):Rsp.fail().msg("修改失败");
    }

    @Override
    public Rsp deleteLogical(User user) {
        user.setDeleted(User.DELETED);
        int result = userMapper.update(user);
        return result == 1?Rsp.success("删除成功"):Rsp.fail().msg("删除失败");
    }

    public Rsp login(User loginUser) {

        //验证账号密码
        String Md5Pwd = DigestUtils.md5DigestAsHex(loginUser.getPassword().getBytes());
        loginUser.setPassword(Md5Pwd);
        User user = userMapper.login(loginUser);

        //验证登录状态
        if (user.getStatus() == User.LOG_ON){
            return Rsp.fail().msg("您已登录");
        }
        if (user.getStatus() == User.LOCK){
            return Rsp.fail().msg("您的账号已被冻结");
        }
        if (user.getDeleted() == User.DELETED){
            return Rsp.fail().msg("该账号已注销");
        }



        if (!StringUtils.isEmpty(user)) {
            try {
                //更改用户登录状态
                user.setStatus(User.LOG_ON);
                update(user);

                //响应一个token
                return Rsp.success(JWTUtil.generateToken(user, Secret.PRIVATE_KEY));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return Rsp.fail().msg("登录失败：账号或密码错误");
        }

        return Rsp.fail().msg("登录失败：账号或密码错误");
    }

    public Rsp logout(String id){
        User user = new User();
        user.setId(id);
        user.setStatus(User.UN_LOG_ON);
        System.out.println(user);
        int result = userMapper.update(user);
        return result == 1?Rsp.success("注销成功"):Rsp.fail().msg("注销失败");
    }

    public Rsp searchSomeRoleByPage(){
        List<Role> roles = userMapper.searchSomeRoleByPage();
        return roles != null?Rsp.success(roles):Rsp.fail().msg("查询失败");
    }

    public Rsp getNextLevelArea(String parentCode){
        List<Area> nextLevelArea = areaMapper.getNextLevelArea(parentCode);
        return nextLevelArea != null?Rsp.success(nextLevelArea):Rsp.fail().msg("查询失败");
    }
    public Rsp getOneLevelArea(Integer level){
        List<Area> areas = areaMapper.getOneLevelArea(level);
        return areas != null?Rsp.success(areas):Rsp.fail().msg("查询失败");
    }

    public Rsp frontLogin(User loginUser) {
        System.out.println(loginUser);

        if (StringUtils.isEmpty(loginUser.getPhone()) || "".equals(loginUser.getPhone())){
            Rsp.fail().msg("手机号不能为空");
        }

        if (StringUtils.isEmpty(loginUser.getPhoneCode()) || "".equals(loginUser.getPhoneCode())){
            Rsp.fail().msg("请填写验证码");
        }
        //验证账号密码
        String Md5Pwd = DigestUtils.md5DigestAsHex(loginUser.getPassword().getBytes());
        loginUser.setPassword(Md5Pwd);
        User user = userMapper.login(loginUser);

        //验证登录状态
        if (user.getStatus() == User.LOG_ON){
            return Rsp.fail().msg("您已登录");
        }
        if (user.getStatus() == User.LOCK){
            return Rsp.fail().msg("您的账号已被冻结");
        }
        if (user.getDeleted() == User.DELETED){
            return Rsp.fail().msg("该账号已注销");
        }

        //从redis拿到手机验证码
        String phoneCode = aliMsgService.isExpire(loginUser.getPhone());

        //验证验证码
        if (StringUtils.isEmpty(phoneCode)){
            return Rsp.fail().msg("验证码已过期，请重新发送");
        }

        if(!loginUser.getPhoneCode().equals(phoneCode)){
            return Rsp.fail().msg("验证码错误");
        }

        if (!StringUtils.isEmpty(user)) {
            try {
                //更改用户登录状态
                user.setStatus(User.LOG_ON);
                update(user);
                //将验证码从redis删除
                redisTemplate.opsForValue().getOperations().delete(loginUser.getPhone());
                //响应一个token
                return Rsp.success(JWTUtil.generateToken(user, Secret.PRIVATE_KEY));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return Rsp.fail().msg("登录失败：账号或密码错误");
        }

        return Rsp.fail().msg("登录失败：账号或密码错误");
    }

    public Rsp updatePwd(String id, String password) {
        return userMapper.updatePwd(id,password)==1?Rsp.success("修改成功"):Rsp.fail().msg("修改失败");
    }
}
